package com.caption.controller;

import com.caption.utils.FastDfsUtils;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/hello")
@Slf4j
public class HelloController {
    @Autowired
    private ThreadPoolTaskExecutor commonExecutor;

    @Autowired
    private FastDfsUtils fastDfsUtils;

    private String host = "http://192.168.1.162:8888";

    @GetMapping("/ping")
    public String ping() {
        String txnId = ThreadContext.peek();
        log.info("访问product模块,交易流水号={}", txnId);
        commonExecutor.submit(() -> {
            int cpu = Runtime.getRuntime().availableProcessors();
            log.info("子线程获取系统核心线程数={}", cpu);
        });
        return "pong=" + txnId;
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/file/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        String path = "";
        try {
            StringBuilder stringBuilder = new StringBuilder();
            StorePath upload = fastDfsUtils.upload(file);
            stringBuilder.append(host).append("/").append(upload.getGroup()).append("/").append(upload.getPath());
            path = stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 删除上传文件
     * path 值 /group1/M00/00/00/1.png
     * @param path
     */
    @PostMapping("/file/delete")
    public Boolean deleteFile(@RequestParam("filePath")String path){
        try{
            fastDfsUtils.delete(path);
            return  true;
        }catch (Exception e){
            log.error(e.getMessage());
           return false;
        }
    }

}
